<?php
/**
 * Created by PhpStorm.
 * User: liuyu
 * Date: 2018/11/19
 * Time: 11:19
 */

namespace app\api\controller\v5;

use app\api\controller\v2\Auth;
use app\common\lib\astrolog\FortunesChange;
use app\common\model\AwardUser;
use app\common\model\Orders;
use app\common\model\Recode;

class FortuneForMonth extends Auth
{
    protected $month_id;

    public function _initialize()
    {
        parent::_initialize();

        $this->month_id = config('goods.month_id');
    }

    /**
     * @return \think\response\Json
     * @throws \app\common\lib\exception\ApiException
     */
    public function index()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }

        $uid = $this->user['id'];
        $rid = input('param.rid/d', 0);
        $year = input('param.year');
        $month = input('param.month');
        //当前查看的时间
        $now_time = strtotime($year . '-' . $month);
        //日历显示时间范围
        $range_start = config('fortune.fortune_time_range')['month']['start'];
        $range_end = config('fortune.fortune_time_range')['month']['end'];


        $OrdersModel = new Orders();
        $AwardUserModel = new AwardUser();
        $RecodeModel = new Recode();

        $map = ['uid' => $uid, 'id' => $rid];
        //获取档案信息
        $recode_info = $RecodeModel->getRecode($map);
        if (!$recode_info || $recode_info['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '档案不存在');
        }
        //解锁状态
        $unlock_status = 0;

        //TODO  是否为VIP用户判断，若为VIP用户，全部解锁且加入计算队列
//        if (in_array($uid, config('vip')))
//        {
//            $time_range = [];
//            $time_range = prDates(['start' => $range_start, 'end' => $range_end, 'type' => 2]);

//            // TODO 判断是否已经加入队列/已经计算完毕
//            // 运势队列消费时需要的数据
//            $jobData = [
//                'recode' =>$recode_info,
//                'start_time' => $year . '-' . $month,
//                'type' => 'month',
//            ];
////            // 运势队列相关配置
//            $fortune_job_setting = config('fortune_job');
////            // VIP 用户加入立即计算队列中 否则 $fortune_job_setting['delay']
//            queuePush($fortune_job_setting['task'],$jobData,$fortune_job_setting['queue'],0);
        // VIP 用户更改为已解锁
//            $unlock_status = 2;
//        } else
//        {
        //获取档案购买的订单
        $orders = $OrdersModel->fortune_orders(['uid' => $uid, 'rid' => $rid, 'type' => 2]);

        //购买订单解锁时间
        $unlock_time = [];
        $order_time = [];
        $unlock_time_range = [];

        if ($orders && !empty($orders))
        {
            //获取档案解锁的信息
            foreach ($orders as $k => $v)
            {
                if ($v['type'] == 2)
                {
                    $extend = json_decode($v['extend'], true);
                    if (isset($extend['expire_time']) && $extend['expire_time'])
                    {
                        $v['expire_time'] = $extend['expire_time'];
                    }
                    $start_time = date('Y-n', $v['time']);
                    $end_time = date('Y-n', strtotime('-1 days', strtotime($v['expire_time'], $v['time'])));

                    $unlock_time['start_time'] = $start_time;
                    $unlock_time['end_time'] = $end_time;

                    $order_time[] = prDates(['start' => $unlock_time['start_time'], 'end' => $unlock_time['end_time'], 'type' => 2]);

                    if (strtotime($start_time) <= $now_time && $now_time <= strtotime($end_time))
                    {
                        $unlock_status = 1;

                        if ($v['status'] == 4)
                        {
                            $unlock_status = 2;
                        }

                    }
                }
            }

            foreach ($order_time as $k => $v)
            {
                foreach ($v as $vv)
                {
                    $unlock_time_range[] = $vv;
                }
            }
        }

        // 获取当前用户的档案id
        $selfId = $RecodeModel->getSelfRecode(['uid' => $this->user['id']]);
        //获取中奖纪录
        $aorders = $AwardUserModel->get_award_fortune(['uid' => $this->user['id'], 'rid' => $rid, 'type' => 3, 'self_id' => $selfId]);

        //中奖解锁时间
        $award_time = [];
        $unlock_award_times = [];
        $award_time_range = [];

        if ($aorders && !empty($aorders))
        {
            // 获取当前用户中奖解锁的时间
            $date = date('Y-n', $now_time);
            //获取用户中奖的信息
            foreach ($aorders as $k => $v)
            {
                $extend = json_decode($v['extend'], true);

                if (in_array($v['aid'], $this->month_id))
                {
                    $start_time = date('Y-n', $extend['award_time']);
                    $end_time = date('Y-n', strtotime('-1 days', strtotime($v['expire_time'], $extend['award_time'])));

                    $award_time['start_time'] = $start_time;
                    $award_time['end_time'] = $end_time;
                    $unlock_award_time = prDates(['start' => $award_time['start_time'], 'end' => $award_time['end_time'], 'type' => 2]);
                    $unlock_award_times[] = $unlock_award_time;

                    if (in_array($date, $unlock_award_time) && $v['status'] == 1)
                    {
                        $unlock_status = 2;
                    } elseif (in_array($date, $unlock_award_time))
                    {
                        $unlock_status = 1;
                    }

                }
            }

            if ($unlock_award_times)
            {
                foreach ($unlock_award_times as $k => $v)
                {
                    foreach ($v as $vv)
                    {
                        $award_time_range[] = $vv;
                    }
                }
            }
        }

        //合并时间
        $time_range = array_merge($unlock_time_range, $award_time_range);
        //时间去重
        $time_range = array_unique($time_range);
        //重新排序
        asort($time_range);
        //重新索引
        $time_range = array_values($time_range);

        //统计订单人数
//        $order_people_num = $OrdersModel->Unlock_people_num(['type' => 2]);
        $fortune_base_num = $OrdersModel->fortune_base(['type' => 1]);

//         暂时全部解锁测试
//
        if ($unlock_status === 2)
        {
            $fortune = (new FortunesChange())->init($recode_info, $year . '-' . str_pad($month, 2, '0', STR_PAD_LEFT));
        } else
        {
            $fortune = [
                'underway_fortune' => [],
                'predicted_fortune' => [],
                'completed_fortune' => [],
            ];
        }


        $data = [
//            'self_rid' => (int)($recode_info['id']),
            'time' => $time_range,
            'underway_fortune' => $fortune['underway_fortune'],
            'predicted_fortune' => $fortune['predicted_fortune'],
            'completed_fortune' => $fortune['completed_fortune'],
            'unlock_num' => (int)($fortune_base_num),
            'unlock_status' => $unlock_status,
            'time_range' => [
                'start_time' => $range_start,
                'end_time' => $range_end,
            ],
        ];

        return show(config('code.success'), '加载成功', $data);
    }
}
